<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用ele画矩形框(橡皮条)</title>
  <style>
    canvas {
      border: 1px solid;
    }
    .rect {
      border: 3px solid #ff0;
      position: absolute;
      display: none;
      width: 0;
      height: 0;
    }
  </style>
</head>
<body>
  <p style="color:red;">mouseup不触发，把事件绑定到body,document上</p>
  <div class="rect"></div>
  <canvas width="800" height="600"></canvas>
  <script>
  var canvas = document.querySelector('canvas'),
      context = canvas.getContext('2d'),
      image = new Image(), // 图片对象
      sp = {}, // 开始点
      ele = document.querySelector('.rect'),
      isdraw = false;

  loadImage();

  canvas.onmousedown = function() {
    event.preventDefault();
    var e = event || window.event;
    sp.x = e.x;
    sp.y = e.y;
    ele.style.left = sp.x  + 'px';
    ele.style.top = sp.y + 'px';
    ele.style.display = 'block';
    isdraw = true;
    console.log("down");
  }

  canvas.onmousemove = function() {
    event.preventDefault();
    var e = event || window.event;
    if(isdraw) {
      ele.style.width = (e.x - sp.x) + 'px';
      ele.style.height = (e.y - sp.y) + 'px';
      console.log("move");
    }
  }

  // 事件在canvas 上面不触发，可以绑到body, document上
  // canvas.onmouseup = function() {
  document.onmouseup = function() {
    event.preventDefault();
    ele.style.display = 'none';
    ele.style.width = 0;
    ele.style.height = 0;
    isdraw = false;
  }

  function loadImage() {
    image.onload = function () {
      // 图片会平铺
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
    }

    image.src = './img/Zhuoku009.jpg';
  }
  </script>
</body>
</html>

